# -*- coding: utf-8 -*-
'''
@Date    : 2022/10/13 14:23
@Author  : Zhaozhengyun
@File    : imagededup.py
@Desc    :包含imagededup算法中的ahash dhash 和phash，
'''

from methods import DHash, AHash, PHash
import shutil
import os

dhasher = DHash()
ahasher = AHash()
phasher = PHash()



def similar(hash1: str, hash2: str) -> float:
    """
    Calculate the hamming distance between two hashes. If length of hashes is not 64 bits, then pads the length
    to be 64 for each hash and then calculates the hamming distance.

    Args:
        hash1: hash string
        hash2: hash string

    Returns:
        hamming_distance: Hamming distance between the two hashes.
    """
    global n

    hash1_bin = bin(int(hash1, 16))[2:].zfill(64)
    hash2_bin = bin(int(hash2, 16))[2:].zfill(64)
    n1 = 0
    for i, j in zip(hash1_bin, hash2_bin):
        if i != j:
            n1 = n1 + 1
    return 1 - n1 / len(hash2_bin)

# def call(arg, *args, **kwargs):
#
#     result = {
#         'sum': arg['x'] + arg['y']
#     }

    # return result


def imagededup(load_folder,save_folder,threshold, algo):
    global  result, result1
    os.makedirs(save_folder, exist_ok=True)
    # print("加载路径为：", arg["load_path"])
    # print("保存路径为：", arg["save_path"])
    # print("阈值为:", arg["threshold"])
    result = {}
    # 生成图像目录中所有图像的二值hash编码，生成字典
    result["msg"] = "检测成功"
    result["code"] = 0
    if algo == "ahash":
        result["algo"] = "ahash"
        encodings = ahasher.encode_images(image_dir=load_folder)
    if algo == "phash":
        result["algo"] = "phash"
        encodings = phasher.encode_images(image_dir=load_folder)
    if algo == "dhash":
        result["algo"] = "dhash"
        encodings = dhasher.encode_images(image_dir=load_folder)
    else:
        # print("hasher参数输入有误，将使用默认dhash")
        result["algo"] = "dhash"
        encodings = dhasher.encode_images(image_dir=load_folder)


    name_list = []
    hash_list = []
    # threshold = 0.85
    # if "threshold" in arg.keys():
    #     threshold = arg["threshold"]

    result1 = []
    try:
        # 取出重复的图片
        file_repeat = []  # 图片两两比较，重复的话后者放在列表中
        result["save_repeat_path"] = save_folder
        for key, value in encodings.items():
            name_list.append(key)
            hash_list.append(value)
        lens = len(name_list)

        # 遍历文件夹里的两两图片比较
        for i in range(0, lens):
            print(i)
            for j in range(i + 1, lens):
                similar1 = similar(hash_list[i], hash_list[j])  # 调用similar函数计算图片之间的相似度
                result[name_list[i] + "和" + name_list[j] + "的similar"] = similar1

                # 判断相似
                if similar1 > threshold:
                    join_result = os.path.join(load_folder, name_list[j])
                    file_repeat.append(join_result)  # 将重复的图片放到file_repeat列表中


        try:
            if len(file_repeat) != 0:  # 如果存在重复的图片则进行去重操作
                # print("*************开始移动重复图片*************")
                for image in file_repeat:
                    file_name = list()  # 新建列表，放原始图片路径
                    for i in os.listdir(load_folder):  # 获取filePath路径下所有文件名
                        name = os.path.join(load_folder, i)

                        file_name.append(name)

                    if image in file_name:  # 如果重复的文件名在原始的文件夹中则进行移动
                        shutil.move(image, save_folder)
                        # print("正在移动重复图片：", image)
                    else:
                        continue
                # print("*************完成移除重复图片*************")
            # else:
                # print("没有重复图片")
            # result["msg"] = "检测成功"
        except:
            # result["msg"] = "检测失败"
            return result
        return result
    except:
        return result